//
//  YiBgCtrl.swift
//  yiplayer
//
//  Created by cgw on 2024/6/25.
//

import UIKit

class YiBgCtrl: UIViewController {
    
    var bgImg = UIImage.init(named: "1")
    private let btmView = YiBgBottomView()
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.setupBgImg(size:self.view.bounds.size)
        
        let eff = UIBlurEffect(style: .dark)
        let blurView = UIVisualEffectView(effect: eff)
        blurView.embedIn(self.view)
        
        btmView.pin(.h(35)).addTo(self.view).makeCons { make in
            make.left.right.bottom.equal(0)
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        let lc = YiHomeListCtrl.init(collectionViewLayout: UICollectionViewFlowLayout())
        lc.modalTransitionStyle = .coverVertical
        lc.modalPresentationStyle = .overFullScreen
        self.present(lc, animated: true)
    }
    
    override var prefersStatusBarHidden: Bool{
        return true
    }
    
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        
        self.setupBgImg(size: size)
        super.viewWillTransition(to: size, with: coordinator)
    }
    
    func setupBgImg(size: CGSize) {
        var img = self.bgImg
        if size.width > size.height {
            img = img?.rotated(by: 90)
        }
        
        if let img = img {
            self.view.layer.contents = img.cgImage
            
            self.view.layer.contentsScale = img.scale
            self.view.layer.contentsGravity = .resizeAspectFill
        }
    }
}

private class YiBgBottomView: UIView {
    let logoImgView = UIImageView()
    let appNameL = UILabel()
    let timeL = UILabel()
    
    var timer: Timer?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.startTimer()
        
        self.addNoti()
        
        self.alpha = 0.4
        
        appNameL.font(12).color(ColorF)
        logoImgView.pin(.wh(18, 18)).img("logo30").radius(9)
        HStack(NERSpring,logoImgView,10,appNameL,NERSpring).embedIn(self).align(.center)
        
        timeL.font(12).color(ColorF).align(.right).addTo(self).makeCons { make in
            make.right.equal(-20)
            make.top.bottom.equal(0)
            make.width.greaterEqual(130)
        }
        
        let na = String.appName() ?? ""
        let v = String.appVersion() ?? ""
        appNameL.text = na + " " + v
    }
    
    func addNoti() {
        NotificationCenter.default.addObserver(self, selector: #selector(inBcakground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(inForground), name: UIApplication.didBecomeActiveNotification, object: nil)
    }
    
    func startTimer() {
        let ti = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timedown), userInfo: nil, repeats: true)
        ti.fire()
        
        self.timer = ti
    }
    
    func stopTimer(){
        self.timer?.invalidate()
        timer = nil
    }
    
    @objc func timedown() {
//        printLog("计时中..")
        let date = NSDate.now
        let d = date.toString(fmt: "HH:mm")
        self.timeL.text = d
    }
    
    @objc func inBcakground() {
        print("进入后台")
        self.stopTimer()
    }
    
    @objc func inForground() {
        print("进入前台")
        self.startTimer()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension UIImage {
    func rotated(by degrees: CGFloat) -> UIImage? {
       guard degrees != 0, let cgImage = self.cgImage else { return self }
       // 计算旋转角度后的新尺寸
       let rotatedViewBox = UIView(frame: CGRect(origin: .zero, size: size))
       rotatedViewBox.transform = CGAffineTransform(rotationAngle: degrees * .pi / 180).concatenating(CGAffineTransform(scaleX: 1, y: -1))
       let rotatedSize = rotatedViewBox.frame.size
       
       // 开始渲染
       UIGraphicsBeginImageContextWithOptions(rotatedSize, false, self.scale)
       defer { UIGraphicsEndImageContext() }
       let bitmap = UIGraphicsGetCurrentContext()!
       bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
       bitmap.rotate(by: degrees * .pi / 180)
       bitmap.scaleBy(x: 1.0, y: -1.0)
       let drawRect = CGRect(origin: CGPoint(x: -size.width / 2, y: -size.height / 2), size: size)
       bitmap.draw(cgImage, in: drawRect)
       return UIGraphicsGetImageFromCurrentImageContext()
    }
}


